home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13538 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  45 lines

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net@castle.nando.net (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursion
  5. Date: Mon, 08 Apr 1996 13:33:56 -0400
  6. Organization: Not so good, but I'm working on it ;-)
  7. Message-ID: <E4UaxUKSAKsW089yn@castle.nando.net>
  8. References: <31624BC2.70D2@sooner.net>
  9. NNTP-Posting-Host: vyger609.nando.net
  10.  
  11. In article <31624BC2.70D2@sooner.net>,
  12. Eddie Bush <edwbush@sooner.net> put down for all to see:
  13.  
  14. >I am trying to construct a C function that will recursively convert
  15. >a string such as "1234" into it's integer equivelant (1234).
  16. >
  17. >Here is what I know:
  18. >1)if you subtract the character "0" from any of the other digits "1".."9"
  19. >  you will get the integer value of that characer.
  20. >    Example:  "1" - "0" is equal to 1
  21. >          "2" - "0" is equal to 2
  22. >          .
  23. >          .
  24. >          .
  25. >          "9" - "0" is equal to 9
  26. >2)the function should be called with a character pointer:
  27. >    Such as:   convert("1234");
  28. >  making the prototype look something like:
  29. >    int convert(char *p);
  30. >
  31. >Does anyone have an idea?  This is sorta stumping me.  I am aware of 
  32. >atoi, but I am wanting to write a recursive function that does that -- 
  33. >for the fun of it.  It's sort of a little puzzle to help me learn 
  34. >recursion.  Any ideas?
  35.  
  36. Here's a simply solution:
  37.  
  38. #include <ctype.h>
  39. int cvt(const char *s, int n) {              
  40.    return isdigit(*s) ? cvt(s+1,10*n+*s-'0') : n;}
  41. int convert(const char *s) {return cvt(s, 0);}
  42.  
  43. Have fun figuring it out,
  44. Bill
  45.